<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of EventModel
 *
 * @author Marko
 */
class Event_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    function event_id_from_raw_competition($raw, $competition_id) {
        $result = mysql_query("SELECT `id` FROM `events` WHERE `competition_id`=$competition_id and `raw`='$raw' ") or die(mysql_error());
        if (mysql_num_rows($result) == 0) {
            return 0;
        }
        return mysql_result($result, 0);
    }

    function event_exists($raw, $competition_id) {
        return ($this->event_id_from_raw_competition($raw, $competition_id) == 0 ? false : true);
    }

    public function generate_raw_string(Event $event, $pool) {
        $pool = ($pool == 25) ? ' SC Meter ' : ' LC Meter ';
        $result = 'event ' . $event->getNr() . ' ' . $this->get_gender_string($event->getGender())
                . ' ' . $this->generate_age_string($event->getLowAge(), $event->getHighAge()) . ' ' . 
                $event->getDistance() . ' ' . $pool . $this->stroke_from_short($event->stroke) . 
                        ($event->isRelay() == 1 ? ' Relay' : '' . ' ' . $event->getType());
        return strtolower(str_replace('  ', ' ', $result));
    }

    public function generate_age_string($low_age, $high_age) {
        if ($low_age == 0 && $high_age == 109) {
            return '';
        } else if ($low_age == 0 || $low_age == 109) {
            return $high_age . ' & under';
        } else if ($high_age == 0 || $high_age == 109) {
            return $low_age . ' & over';
        } else if ($high_age == $low_age) {
            return $low_age;
        } else {
            return $low_age . ' - ' . $high_age;
        }
    }

    public function get_gender_string($gender) {
        switch (strtoupper($gender)) {
            case ('M'): return 'Men';
            case ('F'): return 'Women';
            case ('X'): return 'Mixed';
            default : return '';
        }
    }

    public function stroke_from_short($stroke) {
        switch ($stroke) {
            case 'free':
                return 'Freestyle';
            case 'back':
                return 'Backstroke';
            case 'breast':
                return 'Breaststroke';
            case 'fly':
                return 'Butterfly';
            case 'medley':
                return 'Medley';
            default:
                return '';
        }
    }

    public function populate_events_with_data($events, $competition) {
        $out = array();
        foreach ($events as &$e) {
            $event = new Event();
            foreach ($e AS $key => $value)
                $event->{$key} = $value;
            $event->setCompetitionID($competition->getID());
            $event->setAge($this->generate_age_string($event->getLowAge(), $event->getHighAge()));
            $event->setRaw($this->generate_raw_string($event, $competition->getPool()));
            $event->setFinaBaseTime($competition->getPool(), $event->getDate());
            $out[] = $event;
        }
        return $out;
    }

    /**
     * 
     * @param type $mdb
     * @param Competition $competition
     * @return array(Event)
     */
    public function events_array_from_mdb($mdb, Competition $competition) {
        $query = $mdb->query("SELECT Event_numltr as nr, Rnd_ltr as type, Event_Type,Cint(Event_dist) as distance, 
            Event_strokename, Event_strokecode as stroke_code, Event_gender as gender, 
            Switch(Ind_rel = 'I', 0,Ind_rel = 'R', 1) AS relay, Results.Low_age as low_age, Results.High_Age as high_age 
            FROM Results 
            GROUP BY Event_numltr, Event_dist, Ind_rel, Rnd_ltr, Event_Type,
            Event_strokename, Event_gender, Event_strokecode, Low_age, High_Age 
            ORDER BY Cint(Event_numltr), Low_age");
        $events = $query->result('Event');
        foreach ($events as /* @var $event Event */ &$event) {
            $event->setCompetitionID($competition->getID());
            $event->setAge($this->generate_age_string($event->getLowAge(), $event->getHighAge()));
            $event->setRaw($this->generate_raw_string($event, $competition->getPool()));
//            $event->setStroke($this->stroke_from_code($event->stroke_code, true));
            if (isset($event->event_type) && $event->event_type == 'S') {
                $event->setType('SO');
            }
            $event->setFinaBaseTime($competition->getPool(), $competition->getStartDate());
        }


        return $events;
    }

    /**
     * Parse Event from xml data.
     * @param type $data
     * @return Event or null
     */
    function parse_Event_from_xml($data) {
        if (!empty($data)) {
            $i = 0;
            $eventname = Null;
            do {
                $sections = $data->FormattedArea[0]->FormattedSections[0]->FormattedSection[1];

                if (isset($sections)) {
                    $object = $sections->FormattedReportObjects[0]
                            ->FormattedReportObject[$i];
                }
                if (empty($object)) {
                    break;
                };
                $result = $object->ObjectName;
                switch ($result) {
                    case 'eventname1':
                        $eventname = strval($object->Value);
                        break;
                    default:
                        break;
                }
                $i++;
            } while ($i < 2);
            $i = 0;
            do {
                $sections = $data->FormattedArea[0]->FormattedSections[0]->FormattedSection[3];

                if (isset($sections)) {
                    $object = $sections->FormattedReportObjects[0]
                            ->FormattedReportObject[$i];
                }
                if (empty($object)) {
                    break;
                };
                $result = $object->ObjectName;
                switch ($result) {
                    case 'heat1':
                        $eventname .= ' ' . strval($object->Value);
                        break;
                    default:
                        break;
                }
                $i++;
            } while ($i < 2);
            if ($eventname == null)
                return null;
            return Event::fromRawData($eventname);
        } else {
            return null;
        }
    }

    function insertEventsToDb($events) {
        foreach ($events as /* @var $event Event */ $event) {
            unset($event->finaBaseTime);
            unset($event->event_id);
        }
        if (count($events) != 0) {
            $this->db->insert_batch('events', $events);
        }
    }

    function insert_events_to_db($events) {

        $query = "INSERT INTO `events`(`raw`, `nr`, `distance`, `stroke`, `relay`,
        `age`, `gender`, `competition_id`, `type`, `date`) VALUES ";

        $fields = '';
        foreach ($events as /* @var $event Event */ $event) {
            if (!$this->event_exists($event->getRaw(), $event->getCompetitionID()))
                $fields .= '(\'' . implode('\', \'', $event->toArray()) . '\'), ';
        }
        if ($fields !== '') {
            $fields = substr($fields, 0, strlen($fields) - 2);
            $query .= $fields;
//            echo $query;
            mysql_query($query) or die(mysql_error());
        }
    }

}

?>
